<?php

// @formatter:off
/**
 * @file tag.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-06-03 03:40:32 +0000 (Tue, 03 Jun 2014) $
 *
 * $Id: tag.php 112 2014-06-03 03:40:32Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/services/tags/add/tag.php $
 */
// @formatter:on

require_once __DIR__."/../tools.php";

class WCServiceTagsAddTag extends WCService {
	//
	// Protected variables.
	protected $_tags = array(
		"tags" => array(),
		"required" => array()
	);
	//
	// Class methods.
	public function __construct() {
		parent::__construct();

		$this->_readOnlyConflict = true;

		$this->_requiredParams["url"][] = "group";
		$this->_requiredParams["url"][] = "tag";

		$this->_requiredParams["params"][] = "list";

		$this->_requiredPermissions["to"][] = WC_PERM_TAG_LIST;
		$this->_requiredPermissions["to"][] = WC_PERM_TAG_SET_TAG;
		$this->_requiredPermissions["to"][] = WC_PERM_TAG_ADD;
	}
	//
	// Public methods
	public function check() {
		if(parent::check()) {
			global $wcTag;
			global $wcGroup;

			if(count($this->list) < 1) {
				$this->setError(WC_HTTPERROR_INTERNAL_SERVER_ERROR, "No tags to set");
			}
			if(!$wcGroup || !$wcGroup->ok()) {
				$this->setError(WC_HTTPERROR_INTERNAL_SERVER_ERROR, "There's something wrong with the specified group id");
			}
			if(!$wcTag || !$wcTag->ok()) {
				$this->setError(WC_HTTPERROR_INTERNAL_SERVER_ERROR, "There's something wrong with the specified tag id");
			}
			if($this->ok() && $wcGroup->id != $wcTag->group) {
				$this->setError(WC_HTTPERROR_INTERNAL_SERVER_ERROR, "Unmatching groups");
			}
		}

		return $this->ok();
	}
	//
	// Protected methods.
	public function load() {
		$out = false;

		if(parent::load()) {
			global $wcGroup;

			$this->list = is_array($this->list) ? $this->list : array();
			$this->_tags = tools_modeList($this->list, $wcGroup);

			$out = true;
		}

		return $out;
	}
	protected function runPOST() {
		global $wcErrno;
		global $wcError;
		global $wcGroup;
		global $wcTag;

		tools_filterTags($this->_tags["tags"], WCTagsHolder::I()->tagsOfTag($wcTag));
		//
		// Checking if there are tags to be created.
		$this->_tags["tags"] = array_merge($this->_tags["tags"], tools_createRequiredTags($this->_tags["required"], $wcGroup));

		foreach($this->_tags["tags"] as $tag) {
			$ok = $tag->addTag($wcTag);
			if($wcErrno != 0 && count($this->_tags["tags"]) == 1) {
				$this->setError(WC_HTTPERROR_INTERNAL_SERVER_ERROR, "[{$wcErrno}] {$wcError}", array(
					"errno" => $wcErrno,
					"error" => $wcError
				));
				$ok = false;
			}
			$this->_count += $ok ? 1 : 0;
		}
	}
}
